<?php

class Database
{
	private $_host = 'localhost';
	private $_user = '';
	private $_pass = '';
	private $_db = '';
	private $_obj = null;
	private $_sql = '';
	private $_res = array();
	
	function __construct($settings)
	{
		$this->_user = $settings['username']; //self::_user = $settings['username'];
		$this->_pass = $settings['password'];
		$this->_host = (($settings['host'])?$settings['host']:'localhost');
		$this->_db = $settings['database'];
		
		
		$this->_obj = @mysql_connect($this->_host, $this->_user, $this->_pass);
		if (!is_resource($this->_obj))
			$this->log_error(mysql_error());
		
		mysql_select_db($this->_db) || $this->log_error(mysql_error());
		// for utf-8 support
		@mysql_query("SET NAMES  'utf8';");
	}
	
	private function pre_query($sql, $binds = array())
	{
		if (isset($binds[0]))
			$sql = str_replace(array('?'), $binds, $sql);
		
		$this->_sql = $sql;
		$this->_res = mysql_query($sql, $this->_obj);
		if ($str = @mysql_error($this->_obj))
			$this->log_error($str);
		
		return;
	}
	
	
	private function log_error($sql_msg)
	{
		echo '<pre><b>SQL: </b>'.$this->_sql.'<br /><b>MSG: </b>'.$sql_msg.'</pre>';
		die();
	}
	
	public function debug()
	{
		echo '<pre><b>SQL: </b/> '.$this->_sql.'</pre>';
	}
	
	
	
	
	public function query($sql, $binds = array())
	{
		$this->pre_query($sql, $binds);
		@mysql_free_result();
		return;
	}
	
	public function getOne($sql, $binds = array())
	{
		$this->pre_query($sql, $binds);
		$this->_res = @mysql_fetch_row($this->_res);
		
		@mysql_free_result();
		return $this->_res[0];
	}
	
	public function getRow($sql, $binds = array())
	{
		$this->pre_query($sql, $binds);
		$this->_res = @mysql_fetch_assoc($this->_res);
		
		@mysql_free_result();
		return $this->_res;
	}
	
	public function getCol($sql, $binds = array())
	{
		$this->pre_query($sql, $binds);
		
		$res = array();
		while ($tmp = @mysql_fetch_array($this->_res))
			$res[] = $tmp[0];
		
		@mysql_free_result();
		return $res;
	}
	
	public function getAll($sql, $binds = array())
	{
		$this->pre_query($sql, $binds);
		$res = array();
		
		while ($tmp = @mysql_fetch_assoc($this->_res))
			$res[] = $tmp;
		
		@mysql_free_result();
		return $res;
	}
	
	public function escape($string)
	{
		return mysql_real_escape_string($string);
	}
	
	
	function __destruct(){}
}
?>